###########################################################################
#  Copyright 2010 Jim Pulokas
#
#  This file is part of focusfun.
#  
#  focusfun is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#  
#  focusfun is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with focusfun.  If not, see <http://www.gnu.org/licenses/>.
###########################################################################

numpack = 'Numeric'

if numpack == 'numpy':
	import numpy as num
	uint8 = num.uint8
	float32 = num.float32
	num_buffer_type = num.dtype(uint8)
elif numpack == 'Numeric':
	import Numeric as num
	uint8 = num.UInt8
	float32 = num.Float32
	num_buffer_type = uint8

import Image

def array_to_image(a):
	size = a.shape[1], a.shape[0]
	a = a.astype(uint8)
	im = Image.frombuffer('L', size, a, 'raw', 'L', 0, 1)
	return im

def image_to_array(im):
	im = im.convert('L')
	s = im.tostring()
	shape = im.size[1], im.size[0]
	a = buffer_to_array(s, shape)
	a.shape = im.size[1], im.size[0]
	return a

def buffer_to_array(buffer, shape):
	a = num.fromstring(buffer, num_buffer_type)
	a.shape = shape
	return a

def to_float(a):
	return a.astype(float32)
